package impl

import (
	"encoding/json"
	"github.com/bitly/go-simplejson"
	"io/ioutil"
	"libraryAutoGrab/tool/emailutil"
	"libraryAutoGrab/tool/httputil"
	"net/http"
	"strings"
	"time"
)

type LibraryServiceImpl struct {
}

func NewLibraryServiceImpl() *LibraryServiceImpl {
	libServiceImpl := LibraryServiceImpl{}
	return &libServiceImpl
}

func (libraryServiceImpl *LibraryServiceImpl) Login(userId string, passWord string) string {
	url := "http://202.120.82.17/api.php/login"
	client := &http.Client{}
	body := "username=" + userId + "&password=" + passWord + "&from=mobile"
	request, _ := http.NewRequest("POST", url, strings.NewReader(body))
	httputil.AddLibHeader(request)
	response, _ := client.Do(request)
	all, _ := ioutil.ReadAll(response.Body)
	js, _ := simplejson.NewJson(all)
	token := js.Get("data").Get("_hash_").Get("access_token").MustString()
	defer response.Body.Close()
	return token
}

func (libraryServiceImpl *LibraryServiceImpl) GetSpareTime(area string) string {
	url := "http://202.120.82.17/api.php/space_time_buckets?area=" + area + "&day=" + time.Now().Format("2006-01-02")
	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		panic(err)
	}
	httputil.AddLibHeader(request)
	response, err := client.Do(request)
	defer response.Body.Close()
	all, err := ioutil.ReadAll(response.Body)
	js, err := simplejson.NewJson(all)
	array, err := js.Get("data").Get("list").Array()
	spareTime := array[0].(map[string]interface{})["bookTimeId"].(json.Number).String()
	return spareTime
}

func (libraryServiceImpl *LibraryServiceImpl) GetSpareSeat(area string) []map[string]string {
	day := time.Now().Format("2006-01-02")
	startTime := time.Now().Format("15:04")
	endTime := "23:50"
	url := "http://202.120.82.17/api.php/spaces_old?area=" + area + "&day=" + day + "&startTime=" + startTime + "&endTime=" + endTime
	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		panic(err)
	}
	httputil.AddLibHeader(request)
	response, err := client.Do(request)
	defer response.Body.Close()
	all, err := ioutil.ReadAll(response.Body)
	js, err := simplejson.NewJson(all)
	seats, err := js.Get("data").Get("list").Array()
	var arr []map[string]string
	for _, seat := range seats {
		seatInfo, ok := seat.(map[string]interface{})
		if !ok {
			panic(err)
		}
		if seatInfo["status_name"].(string) == "空闲" {
			arr = append(arr, map[string]string{"id": seatInfo["id"].(json.Number).String(),
				"no": seatInfo["no"].(string)})
		}
	}
	return arr
}

func (libraryServiceImpl *LibraryServiceImpl) BookSeat(token string, userId string, seatId string, segment string) bool {
	client := &http.Client{}
	url := "http://202.120.82.17/api.php/spaces/"+ seatId + "/book";
	body := "access_token=" + token + "&userid=" + userId + "&type=1&id=" + seatId + "&segment=" + segment;
	request, _ := http.NewRequest("POST", url, strings.NewReader(body))
	httputil.AddLibHeader(request) //给request添加头部信息
	response, _ := client.Do(request)
	defer response.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(response.Body)
	js, _ := simplejson.NewJson(bodyBytes)
	status, _ := js.Get("status").Int()
	return status == 1
}

func (libraryServiceImpl *LibraryServiceImpl) AnnounceEmail(email string, list []map[string]string, autoGrab bool) {
	var arr []string
	for _, m := range list {
		arr = append(arr, m["no"])
	}
	emailutil.SendEmail(email, arr, autoGrab)
}
